import websocket
try:
	import thread
except ImportError:
	import _thread as thread
import time
import json
import math
import scipy.io as sio


server = "ws://localhost:9092/websocket"
maximum_time = 10 * 1


tag1_rssi = []
tag2_rssi = []
tag1_phase = []
tag2_phase = []


def phase_read_2_arc(phase):
	return float(phase) * 2 * math.pi / 4096.0


def on_message(ws, message):
	data = json.loads(message)
	if data['type'] == 'readings':
		tag = data['tags'][0]
		tag_id = 1 if tag['epc'] == 'e2000000000000000000000a' else 2
		rssi = tag['rssi']
		
		phase = phase_read_2_arc(tag['phase'])

		if tag_id == 1:
			tag1_phase.append(phase)
			tag1_rssi.append(rssi)
		else:
			tag2_phase.append(phase)
			tag2_rssi.append(rssi)

		print("Tag[{}][{}]: RSSI = {}, Phase = {}".format(tag_id, tag['timestamp'], rssi, phase))


def on_error(ws, error):
	prinr("websocket Error: {}".format(error))


def on_close(ws):
	print("Websocket client closed...")


def on_open(ws):
    def run(*args):
        for i in range(maximum_time):
            time.sleep(1)
            ws.send("Hello %d" % i)
        print("Sample for %ds, thread terminating..." % maximum_time)
        
        name = '0420-2/d-B-water-dis-0-double.mat'
        #name = 'test4'
        sio.savemat(name, {
        	'tag1_rssi': tag1_rssi,
        	'tag2_rssi': tag2_rssi,
        	'tag1_phase': tag1_phase,
        	'tag2_phase': tag2_phase
        	}
        )
        print('File saved... Exit....')

        ws.close()

        
    thread.start_new_thread(run, ())


if __name__ == "__main__":
	# websocket.enableTrace(True)
	ws = websocket.WebSocketApp(server,
		on_message = on_message,
		on_error = on_error,
		on_close = on_close
	)
	ws.on_open = on_open
	ws.run_forever()